package com.itheima03.day11Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 刘全
 * @date 2021/7/31
 */
public class Test5 {
    public static void main(String[] args) throws IOException {
        /**
         * 5. 定义任意字符串数组
         *     统计该数组中所有字符出现的次数，将统计结果输出到当前模块下 count.txt文件中
         *     举例：
         *     String[] str = {"hello","world","java","heiheihei"};
         *
         *     count.txt:
         *         h:4
         *         e:4
         *         l:3
         *         o:2
         *         w:1
         *         r:1
         *         d:1
         *         j:1
         *         a:2
         *         i:3
         *         v:1
         *
         *     提示： 在输出的内容后面加入：\r\n 就有换行效果
         */
        HashMap<Character, Integer> map = new HashMap<>();
        String[] str = {"hello", "world", "java", "heiheihei"};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length; i++) {
            sb.append(str[i]);
        }
        String s = sb.toString();
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (map.containsKey(chars[i])) {
                map.put(chars[i], map.get(chars[i]) + 1);
            } else {
                map.put(chars[i], 1);
            }
        }
        System.out.println(map);
        FileOutputStream fos = new FileOutputStream("myideaTest\\count.txt");
        Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
        for (Map.Entry<Character, Integer> entry : entrySet) {
            Character key = entry.getKey();
            Integer value = entry.getValue();
            String s1 = key + ":" + value + "\r\n";
            byte[] bytes = s1.getBytes();
            fos.write(bytes);
        }
        fos.close();
    }
}
